package com.distribute.core.netty.handler;

import cn.hutool.json.JSONUtil;
import com.distribute.common.MsgObj;
import com.distribute.common.MsgType;
import com.distribute.core.constants.LocalCacheConstants;
import com.distribute.core.monitor.JvmMemoryMessage;
import com.distribute.core.monitor.MemoryStatics;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 内存统计
 *
 * @author chennengcheng
 * @date 2021-09-22 15:49
 * @remark
 */

@ChannelHandler.Sharable
public class MemoryStaticsHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(MemoryStaticsHandler.class);

    public static final int delay_time = 10;

    public static final String jvm_memory_key = "jvm_memory_key";

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Channel channel = ctx.channel();
        channel.eventLoop().scheduleAtFixedRate(() -> {
            // 如果通道正常
            if (channel.isActive()) {
                String str = reportVmMemoryInfo();
                channel.writeAndFlush(str);
            } else {
                channel.closeFuture();
                throw new RuntimeException();
            }

        }, 1, LocalCacheConstants.getReportTime(), TimeUnit.SECONDS);
    }

    /**
     * 上报虚拟机
     */
    public String reportVmMemoryInfo(){
        JvmMemoryMessage jvmMemoryMessage = MemoryStatics.staticsMemory();
        MsgObj msgObj = new MsgObj(MsgType.VM_MEMORY_TYPE, JSONUtil.toJsonStr(jvmMemoryMessage));
        return JSONUtil.toJsonStr(msgObj);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}